package org.syncsoft.overalt.core.api;

import java.util.Collection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.syncsoft.overalt.common.exception.SystemException;
import org.syncsoft.overalt.communication.api.Communication;
import org.syncsoft.overalt.communication.api.ICommunication;
import org.syncsoft.overalt.core.util.XMLConfCore;
import org.syncsoft.overalt.domain.folder.entity.TypeSyncronization;

public class TimerController {
	
	private static TimerController instance;
	
	private final Timer timer;
	
	private final TimerTask task;
	
	static {
		instance = new TimerController();
	}
	
	private TimerController() {
		timer = new Timer();
		this.task = new TimerTask() {
			@Override
			public void run() {
				try {					
					Collection<String> folders = XMLConfCore.getInstance().getFoldersAutomatic();
					
					if(folders != null && folders.size() > 0) {
						
						for(String folderPath: folders) {
							
							String indTypeSync = XMLConfCore.getInstance().getFolderTypeSyncronization(folderPath);
							TypeSyncronization typeSync = TypeSyncronization.getTypeSyncronization(Integer.parseInt(indTypeSync));
							if(typeSync == TypeSyncronization.UPLOAD || typeSync == TypeSyncronization.DOWNLOAD_UPLOAD) {
								getCore().commitFolderFiles(folderPath);
							} 
							
							if(typeSync == TypeSyncronization.DOWNLOAD || typeSync == TypeSyncronization.DOWNLOAD_UPLOAD) {
								try {
									getCore().updateFolderFiles(folderPath);
								} catch (SystemException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							
						}
					}
				} catch (SystemException e){
					
				}
			}
		};
	}
	
	public static TimerController getInstace() {
		return instance;
	}
	
	public void startTimer() throws Exception {
		
		int timeMinutes = XMLConfCore.getInstance().getTimeSync();
		int timeMilliseconds = timeMinutes * 60000;
		timer.scheduleAtFixedRate(task, new Date(), timeMilliseconds);
		
	}
	
	public void stopTimer() {
		task.cancel();
	}
	
	public Core getCore() {
		return Core.getInstance();
	}
	
	public ICommunication getCommunication() {
		return Communication.getInstance();
	}
	
//	public static void main(String args[]) {
//		Scanner input = new Scanner(System.in);
//		System.out.println("0 para STOP");
//		System.out.println("1 para START");
//		while(true) {
//			int i = input.nextInt();
//			if(i == 0) {
//				System.out.println("Stopping");
//				TimerController.getInstace().stopTimer();
//			} else {
//				System.out.println("Startting");
//				try {
//					TimerController.getInstace().startTimer();
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//	}

}
